import { JpaEntity } from './SpringJpaEntity';

export type Pagin = {
  curPage?: number;
  pageSize: number;
};

export type FastQuery<T extends JpaEntity<any>> = {
  clazz: new () => T;
  where?: Partial<T>;
  starSql?: string;
  endSql?: string;
  extParam?: any[];
  pagin?: Pagin;
  order?: { [k in keyof T]?: 'ASC' | 'DESC' };
  isEntity?: boolean;
  update?: (entity: T) => void;
};

export function initFastQuery(query: FastQuery<any>) {
  if (query.isEntity === undefined) query.isEntity = true;
  if (query.where === undefined) query.where = {};
}

export function getUpdateProperty(b: any) {
  //使用解构可以防止继承方法
  let updateProperty: any = {};
  for (let p in b) {
    if (p === 'id' || typeof b[p] === 'function' || b[p] === undefined) {
      continue;
    } else {
      updateProperty[p] = b[p];
    }
  }
  return updateProperty;
}

export function formatPagin(pagin?: Pagin) {
  if (!pagin) return '';
  const { curPage = 1, pageSize } = pagin;
  return `Limit ${(curPage - 1) * pageSize},${pageSize}`;
}

function formatOrder(order?: any) {
  if (!order) return '';
  const orders: string[] = [];
  for (let p in order) {
    orders.push(`${p} ${order[p]}`);
  }
  return `ORDER BY ${orders.join('')}`;
}

export function formatFastQuery<T extends JpaEntity<any>>(
  tableName: string,
  query: FastQuery<T>
) {
  const { where } = query;
  const startSql = query.starSql || `select * from`;
  const endSql = query.endSql || '';
  const propertys: string[] = [];
  const params: any[] = [];
  for (let p in where) {
    propertys.push(`AND ${p}=?`);
    params.push(where[p]);
  }
  const propertySql = propertys.join(' ');
  const orderSql = formatOrder(query.order);
  const paginSql = formatPagin(query.pagin);
  const sql = `${startSql} ${tableName} WHERE 1=1 ${propertySql} ${endSql} ${orderSql} ${paginSql}`;
  return { sql, params };
}

export function formatToEntity<T extends JpaEntity<any>>(
  entityTarget: new () => T,
  data: any
) {
  const entity = new entityTarget();
  Object.assign(entity, data);
  return entity;
}
